﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.ViewModels.AccountAbout;
using Seven.DataModel.ViewModels.UserAbout;
using Seven.Tools.Extension;

namespace Seven.Service.Powerful
{
    public partial class SysUserService
    {
        /// <summary>
        /// 根据登录帐号（用户名或登录别名）获取用户实体，附带员工实体信息
        /// </summary>
        /// <param name="account">登录帐号，可以是用户名或登录别名</param>
        /// <returns></returns>
        public SysUser GetUserByAccount(string account)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                return unit.SysUser.GetUserByAccount(account);
            }
        }

        /// <summary>
        /// 用户登录校验
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="password">登录密码</param>
        /// <returns>业务操作结果</returns>
        public OperationResult CheckLogin(string loginName, string password)
        {
            var userInfo = this.GetUserByAccount(loginName);
            if (userInfo != null)
            {
                if (userInfo.PassWord == new Security.Encrypt().Encode(password))
                {
                    return new OperationResult(true, "登录成功。", userInfo);
                }
                else
                {
                    return new OperationResult(false, "登录密码不正确。");
                }
            }
            else
            {
                return new OperationResult(false, "指定账号的用户不存在。");
            }
        }

        /// <summary>
        /// 检查账号（用户名、登录别名）是否存在
        /// </summary>
        /// <param name="value">账号值</param>
        /// <param name="key">需要忽略的用户的主键值，默认值为0。新增时判定可不传key参数，更新时判定则key传当前用户的主键</param>
        /// <returns></returns>
        public bool CheckAccountNameExist(string value, int key)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                return unit.SysUser.AccountExist(value, key);
            }
        }

        #region 获取ViewModel

        /// <summary>
        /// 获取新的用户模型
        /// </summary>
        /// <returns></returns>
        public UserModel GetNewModel()
        {
            var model = new UserModel();

            return model;
        }

        /// <summary>
        /// 根据用户ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public UserModel GetEditModel(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                return unit.SysUser.GetEditModelByID(id);
            }
        }

        #endregion

        #region 提供json数据

        /// <summary>
        /// 获取用户列表数据
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="deptId">部门ID</param>
        /// <param name="positionId">岗位ID</param>
        /// <param name="roleId">角色ID</param>
        /// <param name="model">序列化的查询条件</param>
        /// <param name="page">页码</param>
        /// <param name="rows">每页条数</param>
        /// <param name="rangeFilter">是否根据管理范围过滤</param>
        /// <returns></returns>
        public JsonResult UserManageGrid(int? companyId, int? deptId, int? positionId, int? roleId, string model, int page, int rows, bool rangeFilter)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var data = unit.SysUser.UserManageGrid(companyId, deptId, positionId, roleId, model, page, rows);
                data = data.Where(w => !w.UserName.Equals(SiteCore.DefaultSuperAdminAccountName, StringComparison.InvariantCultureIgnoreCase));
                return new DataResult(data).SerializeToGridJsonResult(data.Count(), true);
            }
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="model">用户数据模型</param>
        /// <returns>操作结果</returns>
        public JsonResult SaveUser(UserModel model)
        {
            if (model.ID == 0)
            {
                SysUser user = model.CopyTo<SysUser>();
                user.PassWord = new Security.Encrypt().Encode(user.PassWord);
                return this.Insert(user).SerializeToJsonResult();
            }
            else
            {
                SysUser user = this.GetByKey(model.ID);

                user.LoginCode = model.LoginCode;
                user.RoleID = model.RoleID;
                user.Remark = model.Remark;

                return this.Update(user).SerializeToJsonResult();
            }
        }

        /// <summary>
        /// 移除用户【假删除】
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns>操作结果</returns>
        public JsonResult RemoveUser(int id)
        {
            var user = this.GetByKey(id);
            if (user == null) { return new OperationResult(false, true, "用户不存在！").SerializeToJsonResult(); }

            user.IsDeleted = true;
            user.Deleteder = CurrentUserBaseInfo.UserName;
            user.DeletedDate = DateTime.Now;

            return this.Update(user).SerializeToJsonResult();
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="model">密码修改数据模型</param>
        /// <returns>操作结果</returns>
        public JsonResult ModifyUserPassword(PasswordModel model)
        {
            var entity = this.GetByKey(model.UserID); Security.Encrypt En = new Security.Encrypt();
            if (entity.PassWord == En.Encode(model.OldEnPassWord))
            {
                entity.PassWord = En.Encode(model.NewEnPassWord);
                return this.Update(entity).SerializeToJsonResult();
            }
            else
            {
                return new OperationResult(false, "用户原密码不正确！").SerializeToJsonResult();
            }
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="model">密码修改数据模型</param>
        /// <returns>操作结果</returns>
        public JsonResult ResetUserPassword(PasswordModel model)
        {
            var entity = this.GetByKey(model.UserID); Security.Encrypt En = new Security.Encrypt();
            entity.PassWord = En.Encode(model.NewPassWord);
            return this.Update(entity).SerializeToJsonResult();
        }

        /// <summary>
        /// 禁用/启用用户
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="disableState">状态true，则启用；false则禁用</param>
        /// <returns>操作结果</returns>
        public JsonResult EnableOrDisableUser(int id, bool disableState)
        {
            var entity = this.GetByKey(id);
            if (entity == null)
            {
                return new OperationResult(false, "用户不存在！").SerializeToJsonResult();
            }

            entity.IsDisabled = !disableState;
            return this.Update(entity).SerializeToJsonResult();
        }

        #endregion
    }
}
